package com.demo.widget.meis;

import com.demo.widget.ResourceTable;
import com.demo.widget.bean.SmallVideoBean;
import com.meis.widget.photodrag.EasyGirdProvider;
import com.ryan.ohos.extension.widget.viewpager.FractionPagerAdapter;
import com.ryan.ohos.extension.widget.viewpager.ViewPager;
import cs.help.tool.SystemUtil;
import ohos.aafwk.ability.fraction.FractionAbility;
import ohos.aafwk.ability.fraction.FractionManager;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.IntentParams;
import ohos.agp.components.Component;
import ohos.agp.components.Image;
import ohos.agp.components.ListContainer;
import ohos.agp.components.Text;
import ohos.agp.utils.Rect;
import ohos.agp.window.service.WindowManager;
import ohos.global.resource.NotExistException;
import ohos.global.resource.WrongTypeException;
import ohos.utils.PacMap;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by wenshi on 2018/5/29.
 * Description
 */
public class MeiVideoDragListAbility extends FractionAbility {
    ListContainer mRecyclerView;
    EasyGirdProvider<SmallVideoBean> mAdapter;
    ViewPager mViewPager;
    Component toolbar;
    List<SmallVideoBean> mData = new ArrayList<>();
    int mClickPosition = -1;

    private List<SmallVideoBean> getData() {
        if (mData.size() <= 0) {
            for (int i = 0; i < 12; i++) {
                try {
                    SmallVideoBean bean = new SmallVideoBean();
                    bean.title = getResourceManager().getElement(
                            com.meis.widget.ResourceTable.Strarray_small_video_title).getStringArray()[i % 3];
                    bean.coverUrl = getResourceManager().getElement(
                            com.meis.widget.ResourceTable.Strarray_small_video_cover_url).getStringArray()[i % 3];
                    bean.videoUrl = getResourceManager().getElement(
                            com.meis.widget.ResourceTable.Strarray_small_video_video_url).getStringArray()[i % 3];
                    mData.add(bean);
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (NotExistException e) {
                    e.printStackTrace();
                } catch (WrongTypeException e) {
                    e.printStackTrace();
                }
            }
        }
        return mData;
    }

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        setUIContent(ResourceTable.Layout_mei_video_list_ability);
        WindowManager.getInstance().getTopWindow().get().setStatusBarColor(getColor(ResourceTable.Color_colorStatusBar));
        mViewPager = (ViewPager) findComponentById(ResourceTable.Id_view_pager);
        toolbar = findComponentById(ResourceTable.Id_toolbar);
        mRecyclerView = (ListContainer) findComponentById(ResourceTable.Id_recycler);
        initRecyclerView();
        initViewPage();
    }


    private void initRecyclerView() {
        mAdapter = new EasyGirdProvider<SmallVideoBean>(getContext(), ResourceTable.Layout_draglist_itemview, getData()) {
            @Override
            protected void bind(ViewHolder holder, SmallVideoBean s, int position) {
                Image image = (Image) holder.itemView.findComponentById(ResourceTable.Id_iv_bg);
                Text text = (Text) holder.itemView.findComponentById(ResourceTable.Id_tv_name);
                image.setPixelMap(ResourceTable.Media_ic_video_drag_bg);
                text.setText(s.title + position);
            }
        };
        mAdapter.setNumColumns(2);
        mRecyclerView.setItemProvider(mAdapter);
        mAdapter.setOnItemClickListener(new EasyGirdProvider.OnItemClickListener() {
            @Override
            public void onItemClick(Component component, int position) {
                mClickPosition = position;
                int[] locations = ((Component) component.getComponentParent()).getLocationOnScreen();
                Rect globalRect = new Rect();
                component.getSelfVisibleRect(globalRect);
                int[] location = new int[]{locations[0], locations[1] - SystemUtil.getInstance().getStatuBarHeight(), globalRect.right, globalRect.bottom, component.getWidth(), component.getHeight()};
                showFragment(location, position);
            }
        });
    }

    private void showFragment(int[] location, int position) {
        mViewPager.setVisibility(Component.VISIBLE);
        mRecyclerView.setEnabled(false);
        IntentParams intentParams = new IntentParams();
        intentParams.setParam("region", location);
        intentParams.setParam("video_url", mData.get(position % 3).videoUrl);
        intentParams.setParam("index", position);
        intentParams.setParam("position", position);
        getIntent().setParams(intentParams);
        AdapterFragment adapter = (AdapterFragment) mViewPager.getAdapter();
        mViewPager.setCurrentItem(position, false);
        adapter.notifyDataSetChanged(position);
    }

    private void initViewPage() {
        List<MeiVideoDragFragment> mFragments = new ArrayList<>();
        for (int i = 0; i < getData().size(); i++) {
            MeiVideoDragFragment videoDragFragment = new MeiVideoDragFragment(i);
            videoDragFragment.setAnimalListener(new MeiVideoDragFragment.AnimalListener() {
                @Override
                public void animalEnd() {
                    mViewPager.setVisibility(Component.HIDE);
                    mRecyclerView.setEnabled(true);
                }
            });
            mFragments.add(videoDragFragment);
        }
        mViewPager.setOffscreenPageLimit(3);
        mViewPager.setAdapter(new AdapterFragment(getFractionManager(), mFragments));
        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float value, int value1) {
            }

            @Override
            public void onPageSelected(int position) {
                IntentParams intentParams = getIntent().getParams();
                intentParams.setParam("index", position);
                intentParams.setParam("position", position);
                getIntent().setParams(intentParams);
                ((AdapterFragment) mViewPager.getAdapter()).initStart(position);
            }

            @Override
            public void onPageScrollStateChanged(int position) {
            }
        });
    }

    public static class AdapterFragment extends FractionPagerAdapter {
        private List<MeiVideoDragFragment> mFragments;

        public AdapterFragment(FractionManager fm, List<MeiVideoDragFragment> mFragments) {
            super(fm);
            this.mFragments = mFragments;
        }

        @Override
        public MeiVideoDragFragment getItem(int position) {//必须实现
            return mFragments.get(position);
        }

        @Override
        public int getCount() {//必须实现
            return mFragments.size();
        }

        public void notifyDataSetChanged(int position) {
            getItem(position).notifyDataSetChanged();
        }

        public void initStart(int i) {
            for (int j = 0; j < mFragments.size(); j++) {
                mFragments.get(j).initPlay(i);
            }
        }

        @Override
        public void notifyDataSetChanged() {
            super.notifyDataSetChanged();
        }
    }

    @Override
    public void onSaveAbilityState(PacMap outState) {
        outState.putBooleanValue("showViewPager", mViewPager.getVisibility() == Component.VISIBLE);
        outState.putIntValue("nowSelect", mViewPager.getCurrentItem());
        if (getIntent().getParams() != null) {
            outState.putObjectValue("intent", getIntent().getParams());
        }
        super.onSaveAbilityState(outState);
    }

    @Override
    public void onRestoreAbilityState(PacMap inState) {
        super.onRestoreAbilityState(inState);
        if (inState.getBooleanValue("showViewPager")) {
            mViewPager.setVisibility(Component.VISIBLE);
            mViewPager.setCurrentItem(inState.getIntValue("nowSelect"));
            mViewPager.getAdapter().notifyDataSetChanged();
        }
        if (inState.getObjectValue("intent") != null) {
            getIntent().setParams(((IntentParams) inState.getObjectValue("intent").get()));
        }
    }

    @Override
    protected void onBackPressed() {
        if (mViewPager.getVisibility() == Component.VISIBLE) {
            ((AdapterFragment) mViewPager.getAdapter()).getItem(mViewPager.getCurrentItem()).endInExitAnimal();
        } else {
            super.onBackPressed();
        }
    }
}
